Page({
  data: {
    goodsList: [],
    showAddModal: false,
    showEditModal: false,
    addForm: {
      name: '',
      price: '',
      description: '',
      image: ''
    },
    editForm: {
      id: '',
      name: '',
      price: '',
      description: '',
      image: ''
    },
    imagePreview: '',
    editImagePreview: ''
  },
  onLoad() {
    this.getGoodsList();
  },
  getGoodsList() {
    wx.request({
      url: 'http://localhost:3000/api/goods',
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.code === 0) {
          this.setData({ goodsList: res.data.data });
        }
      }
    });
  },
  openAddModal() {
    this.setData({
      showAddModal: true,
      addForm: { name: '', price: '', description: '', image: '' },
      imagePreview: ''
    });
  },
  closeAddModal() {
    this.setData({ showAddModal: false });
  },
  onInput(e) {
    const key = e.currentTarget.dataset.key;
    this.setData({
      [`addForm.${key}`]: e.detail.value
    });
  },
  onEditInput(e) {
    const key = e.currentTarget.dataset.key;
    this.setData({
      [`editForm.${key}`]: e.detail.value
    });
  },
  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          'addForm.image': res.tempFilePaths[0],
          imagePreview: res.tempFilePaths[0]
        });
      }
    });
  },
  chooseEditImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          'editForm.image': res.tempFilePaths[0],
          editImagePreview: res.tempFilePaths[0]
        });
      }
    });
  },
  submitAdd() {
    const { name, price, description, image } = this.data.addForm;
    if (!name || !price || !image) {
      wx.showToast({ title: '请填写完整信息并上传图片', icon: 'none' });
      return;
    }
    wx.uploadFile({
      url: 'http://localhost:3000/api/goods',
      filePath: image,
      name: 'image',
      formData: {
        name,
        price,
        description
      },
      success: (res) => {
        let data = res.data;
        try { data = JSON.parse(res.data); } catch (e) {}
        if (data && data.code === 0) {
          wx.showToast({ title: '新增成功', icon: 'success' });
          this.closeAddModal();
          this.getGoodsList();
        } else {
          wx.showToast({ title: data.message || '新增失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '上传失败', icon: 'none' });
      }
    });
  },
  // 删除商品
  deleteGoods(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要删除该商品吗？',
      success: (res) => {
        if (res.confirm) {
          wx.request({
            url: `http://localhost:3000/api/goods/${id}`,
            method: 'DELETE',
            success: (res) => {
              if (res.data && res.data.code === 0) {
                wx.showToast({ title: '删除成功', icon: 'success' });
                this.getGoodsList();
              } else {
                wx.showToast({ title: res.data.message || '删除失败', icon: 'none' });
              }
            },
            fail: () => {
              wx.showToast({ title: '删除失败', icon: 'none' });
            }
          });
        }
      }
    });
  },
  // 打开编辑弹窗
  editGoods(e) {
    const id = e.currentTarget.dataset.id;
    const goods = this.data.goodsList.find(item => item.id === id);
    this.setData({
      showEditModal: true,
      editForm: {
        id: goods.id,
        name: goods.name,
        price: goods.price,
        description: goods.description,
        image: '', // 新选图片为空
        oldImage: goods.image // 记录原图片
      },
      editImagePreview: goods.image
    });
  },
  closeEditModal() {
    this.setData({ showEditModal: false });
  },
  submitEdit() {
    const { id, name, price, description, image } = this.data.editForm;
    if (!name || !price) {
      wx.showToast({ title: '请填写完整信息', icon: 'none' });
      return;
    }
    if (image) {
      // 有新图片，走上传接口
      wx.uploadFile({
        url: `http://localhost:3000/api/goods/${id}`,
        filePath: image,
        name: 'image',
        formData: { name, price, description },
        method: 'PUT',
        success: (res) => {
          let data = res.data;
          try { data = JSON.parse(res.data); } catch (e) {}
          if (data && data.code === 0) {
            wx.showToast({ title: '编辑成功', icon: 'success' });
            this.closeEditModal();
            this.getGoodsList();
          } else {
            wx.showToast({ title: data.message || '编辑失败', icon: 'none' });
          }
        },
        fail: () => {
          wx.showToast({ title: '上传失败', icon: 'none' });
        }
      });
    } else {
      // 无新图片，普通PUT
      wx.request({
        url: `http://localhost:3000/api/goods/${id}`,
        method: 'PUT',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        data: { name, price, description },
        success: (res) => {
          if (res.data && res.data.code === 0) {
            wx.showToast({ title: '编辑成功', icon: 'success' });
            this.closeEditModal();
            this.getGoodsList();
          } else {
            wx.showToast({ title: res.data.message || '编辑失败', icon: 'none' });
          }
        },
        fail: () => {
          wx.showToast({ title: '编辑失败', icon: 'none' });
        }
      });
    }
  },
  goToOrderManage() {
    wx.navigateTo({
      url: '/pages/admin/order/index'
    });
  }
}); 